
package com.study.spmongodb.thread;

import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/6 13:48
 */
public class StopThread {
    /*private static boolean stopRequested;

    private static synchronized void requestStop() {
        stopRequested = true;
    }

    private static synchronized boolean stopRequested() {
        return stopRequested;
    }

    public static void main(String[] args) throws InterruptedException {
        final Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (!stopRequested()) {
                i++;
            }

        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        requestStop();
    }*/
    private static volatile Boolean stopRequested = Boolean.FALSE;

    public static void main(String[] args) throws InterruptedException {

        final Thread backgroundThread = new Thread(() -> {

            int i = 0;
            while (!stopRequested) {
                i++;
            }
        });

        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}
